<template>
    <div class="add-question-wrap">
        <p>当前选题情况：{{mapQuestionType(questionType)}}<span class="select-num" :class="{'color-1': selectQuestionData.length != limit, 'color-3': selectQuestionData.length == limit}">{{ selectQuestionData.length }}</span>/<span>{{ limit }}</span></p>
        <el-row type="flex" justify="space-between">
            <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
                <el-form-item >
                    <!-- 创建时间 -->
                    <el-date-picker
                        v-model="searchForm.createTime"
                        type="date"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择创建日期"
                        @change="getQuetionBank(1, 10)">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-input
                        placeholder="搜索题干内容"
                        v-model="searchForm.content"
                        @keyup.enter.native="getQuetionBank(1, 10)"
                        clearable>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button class="form-search-btn" type="primary" @click="getQuetionBank(1, 10)">查询</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row type="flex">
            <el-col :span="10">
                <el-table
                    v-loading="loading"
                    border
                    ref="questionBankTable"
                    :data="questionBankData"
                    style="width: 100%"
                    @selection-change="questionBankSelectionChange">
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column label="题干" prop="content" width="260">
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" :content="scope.row.content" placement="bottom">
                                <p class="ell">{{ scope.row.content }}</p>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="createTime"></el-table-column>
                </el-table>
                <el-pagination
                    background
                    small
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    :current-page.sync="currentPage"
                    :page-sizes="[10, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </el-col>
            <el-col class="move-btn-wrap" :span="4">
                <el-button @click="joinSelectList">加入右侧<i class="el-icon-d-arrow-right"></i></el-button>
                <el-button @click="removeSelectList"><i class="el-icon-d-arrow-left"></i>加入左侧</el-button>
            </el-col>
            <el-col :span="10">
                <el-table
                    border
                    ref="selectQuestionTable"
                    :data="selectQuestionData"
                    style="width: 100%"
                    max-height="530"
                    @selection-change="handleSelectionChange">
                    <el-table-column fixed type="selection" width="50"></el-table-column>
                    <el-table-column label="题干" prop="content" width="250">
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" :content="scope.row.content" placement="bottom">
                                <p class="ell">{{ scope.row.content }}</p>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="createTime"></el-table-column>
                </el-table>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import { getQuestionList, getPaperSelectQuestion } from '@/api/exam'

export default {
    name: 'AddQuestion',
    props: {
        questionType: {
            required: true
        },
        configInfo: {
            required: true
        },
        paperId: {
            default() {
                return ''
            }
        }
    },
    data() {
        return {
            limit: 0, // 限制的题数
            searchForm: {
                createTime: '',
                content: ''
            },
            questionBankData: [], // 题库数据
            // 分页
            currentPage: 1,
            pageSize: 10,
            total: 0,
            selectQuestionData: [], // 已选择的题目
            table1Select: [], // 题库中预勾选的试题
            table2Select: [], // 选择试卷中预勾选的试题
        }
    },
    created() {
        this.getQuetionBank()
        // 如果是编辑
        if(this.paperId) {
            // 获取已选择的题目信息
            getPaperSelectQuestion({
                paperId: this.paperId,
                questionType: this.questionType
            }).then(res => {
                if(res.status === 200) {
                    this.selectQuestionData = res.data
                }
            })
        }
    },
    methods: {
        mapQuestionType(key) {
            let MapList = {
                1: '判断题',
                2: '单选题',
                3: '多选题'
            }

            return MapList[key]
        },
        // 获取题库数据
        getQuetionBank(pageIndex, pageSize) {
            let that = this
            that.loading = true
            if (pageIndex) {
                that.currentPage = pageIndex
            }
            if (pageSize) {
                that.pageSize = pageSize
            }
            
            getQuestionList({
                createTime: that.searchForm.createTime || '', // 创建时间
                content: that.searchForm.content, // 题干内容
                type: that.questionType, // 题目类型（ 1判断题 2单选题 3多选题）
                account: that.$store.state.userinfo.accountName, // 当前登录账号
                pageIndex: that.currentPage - 1,
                pageSize: that.pageSize,
                queryType: 1
            }).then(res => {
                if(res.status === 200) {
                    that.questionBankData = res.data
                    that.total = res.total
                    // 已选择的进行选中标记
                    that.$nextTick(() => {
                        res.data.forEach(row => {
                            that.selectQuestionData.forEach(item => {
                                if(row.id == item.id) {
                                    that.$refs.questionBankTable.toggleRowSelection(row)
                                }
                            });
                        });
                    })
                }
                that.loading = false
            })
        },
        handleSizeChange(pageSize) {
            this.getQuetionBank(1, pageSize)
        },
        handleCurrentChange(currentPage) {
            this.getQuetionBank(currentPage)
        },
        // 题库表格勾选的数据变化
        questionBankSelectionChange(val) {
            this.table1Select = val
        },
        // 已选择试题表格勾选的数据变化
        handleSelectionChange(val) {
            this.table2Select = val
        },
        // 加入选择列表中
        joinSelectList() {
            let arr=[]
            // 去掉已选择的试题
            this.table1Select.forEach(m=>{
                if(this.selectQuestionData.filter(n=>{ return n.id==m.id}).length==0){
                    arr.push(m)
                }
            })
            if(this.selectQuestionData.length <= this.limit && arr.length <= this.limit && (this.selectQuestionData.length + arr.length) <= this.limit) {
                // let newArr = $.extend([], this.selectQuestionData, this.table1Select)
                // this.selectQuestionData = newArr
                this.selectQuestionData = this.selectQuestionData.concat(arr)
            } else {
                this.$message.warning(`${this.mapQuestionType(this.questionType)}最多选择${this.limit}道题`)
            }
        },
        // 移除选择列表中
        removeSelectList() {
            let newArr = []
            let selectedList = this.selectQuestionData
            let willRemoveList = this.table2Select

            for(let i=0, len=selectedList.length; i < len; i++) {
                let needRemove = false
                for(let j=0, num=willRemoveList.length; j < num; j++) {
                    if(selectedList[i].id == willRemoveList[j].id) {
                        needRemove = true
                    }
                }
                if(!needRemove) {
                    newArr.push(selectedList[i])
                }
            }
            // 重新设置已勾选试题
            this.selectQuestionData = newArr
            // 清空勾选的试题
            this.table2Select = []
        },
        // 获取数据
        getData() {
            let selectList = this.selectQuestionData
            // 校验配置题数是否正确
            if(selectList.length ==  this.limit) {
                let newArr = []

                for(let i=0, len=selectList.length; i < len; i++) {
                    newArr.push(selectList[i].id)
                }

                return newArr || []
            } else {
                this.$message.warning(`${this.mapQuestionType(this.questionType)}题不得少于${this.limit}道题`)
                return false
            }
        }
    },
    watch: {
        configInfo(val) {
            if(val) {
                let config = JSON.parse(val.questionConfigStr)
                for(let i=0, len=config.length; i < len; i++) {
                    if(config[i].question_type == this.questionType) {
                        this.limit = config[i].question_num
                        break
                    }
                }
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.add-question-wrap {
    .select-num {
        margin-left: 10px;
    }
    .move-btn-wrap {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .el-button {
            margin-left: 0;
            margin-bottom: 10px;
        }
    }
}
</style>
